<template>
  <KyTreeFilter
    ref="kyTreeFilter"
    v-loading="loading"
    :tree-data="treeData"
    @treeChange="treeChange"></KyTreeFilter>
</template>

<script>
import { getItemdicdmbGettypetree } from '@/api/api.js'
import KyTreeFilter from '@/components/treeFilter/index'
const typeKey = 'type'
export default {
  components: {
    KyTreeFilter
  },
  props: {
    hospitalCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      treeData: [],
      initType: ''
    }
  },
  watch: {
    // hospitalCode(val, oldVal) {
    //   if (val) {
    //     this.init()
    //   } else {
    //     this.treeData = []
    //   }
    // }
  },
  created() {
    // this.hospitalCode = this.$store.state.user.hospitalCode
    // this.getTreeData()
  },
  methods: {
    init(initType) {
      this.initType = initType
      this.getTreeData()
      this.reset()
    },
    reset() {
      this.$refs.kyTreeFilter && this.$refs.kyTreeFilter.resetChecked()
    },
    treeChange(data) {
      // console.log(data)
      const selArr = data.split('_')
      let type = ''
      if (selArr.length > 1) {
        selArr.forEach(item => {
          if (item.indexOf(typeKey) >= 0) {
            type = item.split('-')[1]
          }
        })
      }
      this.$emit('treeChange', { type })
    },
    getTreeData() {
      const params = {
        HospitalCode: this.hospitalCode
      }
      this.loading = true
      getItemdicdmbGettypetree(params).then(res => {
        this.loading = false
        if (res) {
          this.treeData = this.treeDataInit(res.content)
          if (this.$hasPermission(['YJYY100050177'])) {
            let items = this.treeData[0].children.filter(item => item.label == '注意事项')
            this.treeData[0].children = items
          }
        }
      })
    },
    treeDataInit(data) {
      let treeData = []
      let treeSelectedId = ''
      if (!data || typeof data !== 'object') {
        return treeData
      } else {
        const hKey = 'hospital-' + data.hospitalCode
        treeData.push({
          id: hKey,
          label: data.hospitalName,
          children: []
        })
        const typeData = data.list
        typeData.forEach((type, tIndex) => {
          const aKey = `${hKey}_${typeKey}${tIndex}-${type}`
          if ((!this.initType && tIndex === 0) || this.initType === type) { treeSelectedId = aKey }
          const typeObj = {
            id: aKey,
            label: type,
            children: []
          }
          treeData[0].children.push(typeObj)
        })
        if (treeSelectedId) {
          this.treeChange(treeSelectedId)
          this.$nextTick(() => {
            this.$refs.kyTreeFilter && this.$refs.kyTreeFilter.resetChecked(treeSelectedId)
          })
          this.initType = ''
        }
        console.log('treeData', treeData)
        return treeData
      }
    }
  }
}
</script>

<style>

</style>
